package com.snail.wifiadb;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button mSetWifiAdb = null;
    private Button mReset = null;
    private TextView mIpView = null;
    private String  mIp = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSetWifiAdb = (Button)findViewById(R.id.setwifiadb);
        mReset = (Button)findViewById(R.id.reset);
        mIpView = (TextView)findViewById(R.id.ip);
        mSetWifiAdb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String cmd = "setprop service.adb.tcp.port 5555;stop adbd;start adbd;\n";
                excuteCmd(cmd);
            }
            
        });
        
        
        mReset.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String cmd = "setprop service.adb.tcp.port ' ';stop adbd;start adbd;\n";
                excuteCmd(cmd);
            }
            
        });
        
        new Thread() {
            public void run() {
                mIp = getIP();
                mIpView.setText(mIp);
            }
        }.start();
        
    }

    private void excuteCmd(String cmd) {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream outstream =  new DataOutputStream(process.getOutputStream());
            outstream.writeBytes(cmd);
            outstream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private String getIP() {
        Socket socket = null;
        try {
            socket = new Socket("www.baidu.com", 80);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(socket==null)
            return " ";
        return socket.getLocalAddress().toString();
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
